import {PageContainer} from "@ant-design/pro-layout";
import type {ProColumns} from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import {getPermissionGroup, getPermissions, getPermissionsByGroup} from "@/services/abis/permission";
import {useRequest} from "@@/plugin-request/request";
import {useState} from "react";

const columns: ProColumns<ABIS.Permission>[] = [
  {
    title: '序号',
    dataIndex: 'id',
    align: "center"
  },
  {
    title: '权限组',
    dataIndex: 'group'
  },
  {
    title: '权限组名称',
    dataIndex: 'group_label',
  },
  {
    title: '权限',
    dataIndex: 'permission'
  },
  {
    title: '权限名称',
    dataIndex: 'label',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    render: (_, record) => {
      return record.created_at.replace('T', ' ')
    }
  },
  {
    title: '最后更新时间',
    dataIndex: 'updated_at',
    render: (_, record) => {
      return record.updated_at?.replace('T', ' ')
    }
  }
]

export default () => {
  const {data} = useRequest(getPermissionGroup)
  const permissionGroup: { key: string; label: string; }[] = [{key: '/', label: '全部权限组'}]

  data?.map(value => {
    permissionGroup.push({key: value.group, label: value.label})
  })

  const [selectGroup, setSelectGroup] = useState('')

  return (
    <>
      <PageContainer>
        <ProTable<ABIS.Permission>
          columns={columns}
          rowKey={record => record.id}
          cardBordered={true}
          search={false}
          toolbar={{
            menu: {
              type: "dropdown",
              items: permissionGroup,
              onChange: key => {
                console.log(key)
                setSelectGroup(key as string)
              }
            }
          }}
          params={{
            group: selectGroup
          }}
          request={async (params) => {
            let permissions: ABIS.Pagination<ABIS.Permission>
            if (params.group && params.group !== '/') {
              permissions = await getPermissionsByGroup(params.group, params.current, params.pageSize)
            } else {
              permissions = await getPermissions(params.current, params.pageSize);
            }
            return {
              data: permissions.data.list,
              success: permissions.code === 1000,
              total: permissions.data.total
            }
          }}
          pagination={{
            hideOnSinglePage: false
          }}
        />
      </PageContainer>
    </>
  )
}
